<template>
  <div class="app-container">
    <el-card class="box-card">
      <!-- 表单 -->
      <el-form
        ref="ruleForm"
        :model="dataForm"
        :rules="dataRules"
        label-width="130px"
        style="margin-top:30px"
      >
        <el-form-item label="重置密码" prop="password">
          <el-input v-model="dataForm.password" style="width:30%" show-password placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="再次输入密码" prop="passwordTry">
          <el-input
            v-model="dataForm.passwordTry"
            style="width:30%"
            show-password
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">立即修改</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { confirm } from '@/config/publicMethod'
import { updateUserInfoRequest } from '@/api/other'
export default {
  data() {
    return {
      dataForm: {
        password: '',
        passwordTry: '',
        id: '',
      },
      dataRules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码的长度在6~15个字符之间',
            trigger: 'blur',
          },
        ],
        passwordTry: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码的长度在6~15个字符之间',
            trigger: 'blur',
          },
        ],
      },
    }
  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      const { userObj } = this.$store.state && this.$store.state.user
      this.dataForm.id = userObj.id
    },
    handleSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return
        const { password, passwordTry } = this.dataForm
        if (password !== passwordTry)
          return this.$message.info('两次输入密码不一致!')
        let data = {
          password: this.dataForm.password,
          id: this.dataForm.id,
        }
        const res = await confirm('确定修改密码')
        if (res) {
          updateUserInfoRequest(data).then((res) => {
            const { code, msg } = res
            if (code !== '0000') return this.$message.error(msg)
            this.dialogVisible = false
            this.$message.success('密码重置成功')
            setTimeout(async (_) => {
              await this.$store.dispatch('user/logout')
              this.$router.push(`/login?redirect=${this.$route.fullPath}`)
            }, 1500)
          })
        }
      })
    },
    handleReset() {
      this.dataForm.password = ''
      this.dataForm.passwordTry = ''
    },
  },
}
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 30px;
}
</style>
